package com.yst.web.utils;

import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

public class EventBusUtils {
    public interface Callback{
        void onEvent(String key,Object caller);
    }
    private static final Hashtable<String, List<Callback>> events=new Hashtable<String, List<Callback>>();

    public static void onEvent(String key,Callback callback){
        List<Callback> callbacks= events.computeIfAbsent(key,(v)->{
            List<Callback> list=new LinkedList<>();
            list.add(callback);
            return list;
        });
        if (!callbacks.contains(callback)){
            callbacks.add(callback);
        }
    }

    public static void onEvent(String[] keys,Callback callback){
        for (String key:keys) {
            List<Callback> callbacks = events.computeIfAbsent(key, (v) -> {
                List<Callback> list = new LinkedList<>();
                list.add(callback);
                return list;
            });
            if (!callbacks.contains(callback)) {
                callbacks.add(callback);
            }
        }
    }

    public static void notify(Object caller,String...keys){
        for (String key:keys) {
            List<Callback> callbacks = events.get(key);
            if (Objects.nonNull(callbacks)) {
                callbacks.forEach((callback -> callback.onEvent(key, caller)));
            }
        }
    }
}
